package com.ipay.foreign.controller;

import com.alibaba.fastjson.JSON;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradeWapPayRequest;
import com.ipay.common.Base64Coder;
import com.ipay.entity.BizSequenceType;
import com.ipay.foreign.pojo.MerchantPayParameter;
import com.ipay.foreign.service.MerchantPayParameterService;
import com.ipay.service.impl.DefaultSequenceManager;
import com.ipay.utils.*;
import com.ipay.wechat.component.Wechat;
import com.ipay.wechat.factory.AuthorizeFactory;
import com.ipay.wechat.pojo.MerchantInfoEntity;
import com.ipay.wechat.service.MerchantInfoService;
import com.ipay.wechat.service.PayorderService;
import com.sun.jndi.toolkit.url.Uri;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

/**
 * 授权
 *
 * @author Administrator
 */
@Controller
public class AuthorizeAPIController {
    private Logger logger = LoggerFactory.getLogger(getClass());
    @Autowired
    private AuthorizeFactory auFatory;
    @Autowired
    private Wechat wechat;
    @Autowired
    private MerchantInfoService merchantInfoService;
    @Autowired
    private MerchantPayParameterService merchantPayParameterService;
    @Autowired
    private PayorderService payorderService;

    /**
     * 第三方发起支付请求
     * 商户表添加来源  +  加密key  +
     *
     * @param request
     * @return https://www.***.cn/wechat/merchant/userAgent?merchantNo=D2017103112000000012&codeNo=20171031205938
     * &sponsorOrderNo=D2017103114000000999&payMoney=20&payremark=国外旅保险定点&notifyUrl=&sign=
     */
    @RequestMapping(value = "/merchant/payGateway", method = RequestMethod.GET)
    public ModelAndView getPayGateway(HttpServletRequest request) throws Exception {
        Map<String, String> map = new HashMap<String, String>();
        String payId = request.getParameter("payId");//支付参数id
        String sign = request.getParameter("sign");//签名+key
        MerchantPayParameter merchantPayParameter = merchantPayParameterService.queryObject(payId);

        if (merchantPayParameter == null || StringUtil.isEmpty(merchantPayParameter.getMerchantNo())) {
            return new ModelAndView("pay/payError.jsp").addObject("errorMesage", "订单信息错误");
        }
        map.put("merchantNo", merchantPayParameter.getMerchantNo());
        map.put("codeNo", merchantPayParameter.getCodeNo());
        map.put("sponsorOrderNo", merchantPayParameter.getSponsorOrderNo());
        map.put("payMoney", String.valueOf(merchantPayParameter.getPayMoney()));
        String payremarkEncode = URLEncoder.encode(merchantPayParameter.getPayremark(), "utf-8");///订单说明
        map.put("payremark", payremarkEncode);
        map.put("callbackUrl", merchantPayParameter.getCallbackUrl());
        map.put("notifyUrl", merchantPayParameter.getNotifyUrl());

        String strtosign = MapUtils.formatUrlMap(map, false, false);
        MerchantInfoEntity merchantInfo = merchantInfoService.queryObject(merchantPayParameter.getMerchantNo());
        if (merchantInfo == null || StringUtil.isEmpty(merchantInfo.getMerchantNo()) || StringUtil.isEmpty(merchantInfo.getPayKey())) {  ///记得替换判断加密参数key是否为空
            return new ModelAndView("pay/payError.jsp").addObject("errorMesage", "商户信息错误");
        }
        //TODO 查询商户相关数据  =payKey
        String parameter = Base64Coder.encode(strtosign);
        String signstr = MD5.sign(parameter, "&payKey=" + merchantInfo.getPayKey(), "utf-8");
        logger.info("=======================signstr:" + signstr + "   =   sign:" + sign + "   =   " + (signstr.equals(sign)));
        if (!signstr.equals(sign)) {
            return new ModelAndView("pay/payError.jsp").addObject("errorMesage", "签名错误");
        } else {
            String params = "?payId=" + payId + "&sign=" + sign + "&merchantNo=" + merchantPayParameter.getMerchantNo() + "&codeNo=" + merchantPayParameter.getCodeNo();
            String ua = request.getHeader("User-Agent");
            String post_url = "";
            if (ua.indexOf("MicroMessenger") > 0) {
                // 微信
                post_url = auFatory.dealAuthorize("payGateway", params);
            } else if (ua.indexOf("AlipayClient") > 0) {
                // 支付宝
                post_url = auFatory.createAliPostUrl("payGateway", params);
            } else {
                return new ModelAndView("pay/payError.jsp").addObject("errorMesage", "暂时我们只开通了微信，支付宝支付功能！后续我们会相继开通其它支付渠道");
            }
            logger.info("post_url------------" + post_url);
            return new ModelAndView("redirect:" + post_url);
        }
    }

    /**第三方发起支付请求
     * @param merchantNo         商户号
     * @param codeNo             收款码编号
     * @param request
     * @param redirectAttributes
     * @throws UnsupportedEncodingException https://www.***.cn/wechat/merchant/userAgent?merchantNo=D2017103112000000012
     */
    @RequestMapping(value = "/auth/payGateway", method = RequestMethod.GET)
    public ModelAndView payAuthRedirect(@RequestParam String merchantNo, @RequestParam String codeNo, HttpServletRequest request,
                                        final RedirectAttributes redirectAttributes) throws Exception {
        String ua = request.getHeader("User-Agent");
        if (ua.indexOf("MicroMessenger") > 0) {// 微信
            redirectAttributes.addAttribute("User-Agent", "MicroMessenger");
        } else if (ua.indexOf("AlipayClient") > 0) {// 支付宝
            redirectAttributes.addAttribute("User-Agent", "AlipayClient");
        } else {
            return new ModelAndView("pay/payError.jsp").addObject("errorMesage", "暂时我们只开通了微信，支付宝支付功能！后续我们会相继开通其它支付渠道");
        }
        logger.info("merchantNo-----" + merchantNo + "baseUrl-----" + wechat.getBaseUrl());
        Map<String, String> map = new HashMap<String, String>();
        String payId = request.getParameter("payId");//支付参数id
        String sign = request.getParameter("sign");//签名+key
        MerchantPayParameter merchantPayParameter = merchantPayParameterService.queryObject(payId);

        if (merchantPayParameter == null || StringUtil.isEmpty(merchantPayParameter.getMerchantNo())) {
            return new ModelAndView("pay/payError.jsp").addObject("errorMesage", "订单信息错误");
        }
        map.put("merchantNo", merchantPayParameter.getMerchantNo());
        map.put("codeNo", merchantPayParameter.getCodeNo());
        map.put("sponsorOrderNo", merchantPayParameter.getSponsorOrderNo());
        map.put("payMoney", String.valueOf(merchantPayParameter.getPayMoney()));
        String payremarkEncode = URLEncoder.encode(merchantPayParameter.getPayremark(), "utf-8");///订单说明
        map.put("payremark", payremarkEncode);
        map.put("callbackUrl", merchantPayParameter.getCallbackUrl());
        map.put("notifyUrl", merchantPayParameter.getNotifyUrl());

        String strtosign = MapUtils.formatUrlMap(map, false, false);
        MerchantInfoEntity merchantInfo = merchantInfoService.queryObject(merchantPayParameter.getMerchantNo());
        if (merchantInfo == null || StringUtil.isEmpty(merchantInfo.getMerchantNo()) || StringUtil.isEmpty(merchantInfo.getPayKey())) {  ///记得替换判断加密参数key是否为空
            return new ModelAndView("pay/payError.jsp").addObject("errorMesage", "商户信息错误");
        } else {
            //TODO 查询商户相关数据  =payKey
            String parameter = Base64Coder.encode(strtosign);
            String signstr = MD5.sign(parameter, "&payKey=" + merchantInfo.getPayKey(), "utf-8");
            logger.info("=======================signstr:" + signstr + "   =   sign:" + sign + "   =   " + (signstr.equals(sign)));
            if (!signstr.equals(sign)) {
                return new ModelAndView("pay/payError.jsp").addObject("errorMesage", "签名错误");
            }
            redirectAttributes.addAttribute("sponsorOrderNo", merchantPayParameter.getSponsorOrderNo());//发起方订单号
            redirectAttributes.addAttribute("payMoney", merchantPayParameter.getPayMoney());////付款金额
            redirectAttributes.addAttribute("payremark", payremarkEncode);//订单说明
            redirectAttributes.addAttribute("notifyUrl", merchantPayParameter.getNotifyUrl());//回调地址
            redirectAttributes.addAttribute("sign", sign);//签名+key
            redirectAttributes.addAttribute("payId", payId);//支付参数id

            redirectAttributes.addAttribute("codeNo", codeNo);//收款员编号
            redirectAttributes.addAttribute("merchantId", merchantNo);//商家编号
            redirectAttributes.addAttribute("openid", request.getSession().getAttribute("openid"));//用户唯一标示
            request.setCharacterEncoding("utf-8");
            String shopName = "";
            if (StringUtil.isNotEmpty(merchantInfo.getShopName())) {
                shopName = URLEncoder.encode(merchantInfo.getShopName(), "utf-8");
            }
            logger.info("shopName----" + shopName + "-----logo-----" + merchantInfo.getLogo());
            redirectAttributes.addAttribute("logo", merchantInfo.getLogo());
            redirectAttributes.addAttribute("shopName", shopName);
        }
        redirectAttributes.addAttribute("baseUrl", wechat.getBaseUrl());
        redirectAttributes.addAttribute("baseUrlWechat", wechat.getBaseUrlWechat());
        //return new ModelAndView("redirect:" + wechat.getBaseUrl() + "pay/pay.html");
        return new ModelAndView("redirect:" + wechat.getBaseUrlWechat() + "pay.html");////暂时修改  银行修改渠道参数配置后记得修改
    }


    /**
     * 测试方法
     * https://www.***.cn/wechat/auth/pay?merchantNo=D2017103111000000011&codeNo=20171031205938
     * D2017122515000000041 20171225012829
     */
    @RequestMapping(value = "/auth/pay", method = RequestMethod.GET)
    public ModelAndView pay(@RequestParam String merchantNo, @RequestParam String codeNo) throws Exception {
        MerchantInfoEntity merchantInfo = merchantInfoService.queryObject(merchantNo);
        if (merchantInfo == null || StringUtil.isEmpty(merchantInfo.getMerchantNo()) || StringUtil.isEmpty(merchantInfo.getPayKey())) {  ///记得替换判断加密参数key是否为空
            return new ModelAndView("pay/payError.jsp").addObject("errorMesage", "商户信息错误");
        }
        String sponsorOrderNo = DefaultSequenceManager.get().next(BizSequenceType.TRANSQ);//订单号
        logger.info("==/auth/pay=付款订单号====sponsorOrderNo:" + sponsorOrderNo);
        String notifyUrl = "https://www.***.cn/pay-manager/bankInfo/doCallbackNotify";
        Map<String, String> map = new HashMap<String, String>();
        map.put("merchantNo", merchantNo);//商户编号
        map.put("codeNo", codeNo);//收款员编号
        map.put("sponsorOrderNo", sponsorOrderNo);//付款订单号
        map.put("payMoney", "0.01");//付款金额
        map.put("callbackUrl", wechat.getBaseUrl()+"auth/isMerchant");//前台通知地址
        map.put("notifyUrl", notifyUrl);//回调地址（订单状态）
        String payremark = URLEncoder.encode("国外旅泰国旅游保险", "utf-8");///订单说明
        map.put("payremark", payremark);

        System.out.println("wxJsPay====:" + JSON.toJSONString(map));
        String strtosign = MapUtils.formatUrlMap(map, false, false);
        //TODO 查询商户相关数据
        String parameter = Base64Coder.encode(strtosign);
        String signstr = MD5.sign(parameter, "&payKey=" + merchantInfo.getPayKey(), "utf-8");
        System.out.println("====/auth/pay======signstr===========:" + signstr);
        map.put("sign", signstr);
        String param = strtosign + "&sign=" + signstr;
        System.out.println("====/auth/pay======param===========:" + param);
        String redirectUrl = wechat.getBaseUrl() + "auth/payView?" + param;//Constant.DOMAINURL_HTTPS
        System.out.println("====/auth/pay===*************************===param===========:" + redirectUrl);
        //String redirectUrl = "http://localhost:8081/auth/payView?" + param;
        return new ModelAndView("redirect:" + redirectUrl);
    }

    /**
     * 进入支付页面
     * https://www.***.cn/wechat/auth/pay?merchantNo=D2017103111000000011&codeNo=20171031205938
     */
    @RequestMapping(value = "/auth/payView", method = RequestMethod.GET)
    public ModelAndView pay(HttpServletRequest request, ModelMap modeMap) throws Exception {
        String sponsorOrderNo = request.getParameter("sponsorOrderNo");//发起方订单号
        String payMoney = request.getParameter("payMoney");////金额
        String codeNo = request.getParameter("codeNo");//收款员编号
        String merchantNo = request.getParameter("merchantNo");//商户编号
        String callbackUrl = request.getParameter("callbackUrl");//前台通知地址
        String notifyUrl = request.getParameter("notifyUrl");//后台通知地址（订单状态）
        String payremark = request.getParameter("payremark");////订单说明  商品描叙
        String sign = request.getParameter("sign");//签名

        Map<String, String> map = new HashMap<String, String>();
        map.put("merchantNo", merchantNo);//商户编号
        map.put("codeNo", codeNo);//收款员编号
        map.put("sponsorOrderNo", sponsorOrderNo);//付款订单号
        map.put("payMoney", payMoney);//付款金额
        map.put("callbackUrl", callbackUrl);//前台通知地址
        map.put("notifyUrl", notifyUrl);//回调地址（订单状态）
        String payremarkEncode = URLEncoder.encode(payremark, "utf-8");///订单说明
        map.put("payremark", payremarkEncode);
        String strtosign = MapUtils.formatUrlMap(map, false, false);
        MerchantInfoEntity merchantInfo = merchantInfoService.queryObject(merchantNo);
        if (merchantInfo == null || StringUtil.isEmpty(merchantInfo.getMerchantNo()) || StringUtil.isEmpty(merchantInfo.getPayKey())) {  ///记得替换判断加密参数key是否为空
            return new ModelAndView("pay/payError.jsp").addObject("errorMesage", "商户信息错误");
        }
        //TODO 查询商户相关数据  =payKey
        String parameter = Base64Coder.encode(strtosign);
        String signstr = MD5.sign(parameter, "&payKey=" + merchantInfo.getPayKey(), "utf-8");
        if (StringUtil.isNotEmpty(sign) && sign.equals(signstr)) {
            modeMap.put("sponsorOrderNo", sponsorOrderNo);//订单号
            modeMap.put("payMoney", payMoney);//订单金额
            modeMap.put("callback_url", callbackUrl);///前段回调地址
            modeMap.put("payremark", payremark);///订单说明
            modeMap.put("shopName", merchantInfo.getShopName());///店铺名称
            modeMap.put("codeNo", codeNo);///店铺名称
            ///保存请求数据
            MerchantPayParameter merchantPay = new MerchantPayParameter();
            merchantPay.setSponsorOrderNo(sponsorOrderNo);
            merchantPay.setCodeNo(codeNo);
            merchantPay.setMerchantNo(merchantNo);
            merchantPay.setPayMoney(new BigDecimal(payMoney));
            merchantPay.setCallbackUrl(callbackUrl);
            merchantPay.setNotifyUrl(notifyUrl);
            merchantPay.setPayremark(payremark);
            merchantPay.setSign(signstr);
            merchantPay.setStart(Constant.START_WZF);//发起 订单状态（0未支付，1支付中，2已支付，3已取消）
            merchantPay.setTypes(Constant.TYPES_DSFPC);//发起类型（0第三方pc端，1收款员生成固额二维码）
            merchantPayParameterService.save(merchantPay);
            logger.info("===========id:" + merchantPay.getId());
            logger.info("=====********************************======id:" + merchantPay.getId());
            modeMap.put("payId", merchantPay.getId());////商户编号
            modeMap.put("sign", signstr);////签名
            return new ModelAndView("pay/payView.jsp");
        } else {
            modeMap.put("payremark", payremarkEncode);///订单说明
            return new ModelAndView("pay/payView.jsp");
        }
    }

    /**
     * 二维码
     *
     * @param request
     * @param response
     * @param payId    //支付参数id
     * @param sign     //签名
     */
    @RequestMapping("/auth/lookPayUrl")
    public void lookPayUrl(HttpServletRequest request, HttpServletResponse response, @RequestParam String payId, @RequestParam String sign) {
        response.setContentType("image/jpeg");
        try {
            String postUrl = wechat.getBaseUrl() + "merchant/payGateway?payId=" + payId + "&sign=" + sign;//Constant.DOMAINURL_HTTPS
            logger.info("====postUrl:" + postUrl);
            com.ipay.core.QRCode.printQRCodeByLogo(response.getOutputStream(), postUrl);
        } catch (IOException e) {
            logger.error("查看二维码输出异常：", e);
        }
    }

    /**
     * ajax查询订单状态
     */
    @RequestMapping(value = "/auth/findOrderStart", method = RequestMethod.POST)
    @ResponseBody
    public R findOrderStart(@RequestParam String payId) {
        System.out.println("============payId:" + payId);
        MerchantPayParameter merchantPayParameter = merchantPayParameterService.queryObject(payId);
        if (merchantPayParameter != null && StringUtil.isNotEmpty(merchantPayParameter.getStart())) {
            return R.ok().put("status", merchantPayParameter.getStart());////发起 订单状态（0未支付，1支付中，2已支付，3已取消）
        } else {
            return R.error("");
        }
    }


    //////////////////////////////////扫码支付//////////////////////////////////
    /**
     * 保存本系统订单
     * Busid 商户ID
     */
    /*@RequestMapping(value = "/merchant/userNative", method = RequestMethod.POST)
	@ResponseBody
	@IgnoreAuth
	public R getUserNative(@RequestBody PayParameter payParameter,HttpServletRequest request) {
*//*
		商户号	mch_id	是	String(32)	商户号，由平台分配
		商户订单号	out_trade_no	是	String(32)	商户系统内部的订单号 ,32个字符内、 可包含字母,确保在商户系统唯一
		商品描述	body	是	String(127)	商品描述
		总金额	total_fee	是	Int	总金额，以分为单位，不允许包含任何字、符号
		终端IP	mch_create_ip	是	String(16)	订单生成的机器 IP
		页面展示通知地址	return_url	是	String(255)	页面同步跳转地址
		后台通知地址	notify_url	是	String(255)	接收平台通知的URL，需给绝对路径，255字符内格式如:http://wap.tenpay.com/tenpay.asp，确保平台能通过互联网访问该地址
		签名	sign	是	String(32)	MD5签名结果，详见“安全规范”*//*

		if (StringUtil.isBlank(payParameter.getMch_id()) || StringUtil.isBlank(payParameter.getOut_trade_no()) ||
				StringUtil.isEmpty(payParameter.getBody())||StringUtil.isBlank(payParameter.getTotal_fee()) ||
				StringUtil.isBlank(payParameter.getMch_create_ip()) || StringUtil.isBlank(payParameter.getNotify_url()) ||
				StringUtil.isBlank(payParameter.getSign())  || StringUtil.isBlank(payParameter.getOut_trade_no())  ) {
			return R.error("支付请求数据错误");
		}
		logger.info("getMch_id()=======:" + payParameter.getMch_id());
		MerchantInfoEntity merchant = merchantInfoService.queryObject(payParameter.getMch_id());
		if (merchant == null || StringUtil.isEmpty(merchant.getMerchantNo())||StringUtil.isEmpty(merchant.getPayKey())) {
			return R.error("商户资料获取失败");
		}
		///我们通信签名验证
		Map<String,String> map=new HashMap<String,String>();
		map.put("mch_id",payParameter.getMch_id());//商户号
		map.put("out_trade_no",payParameter.getOut_trade_no());//商户订单号
		map.put("body",payParameter.getBody());//商品描述
		map.put("total_fee", String.valueOf(payParameter.getTotal_fee()));//总金额
		map.put("mch_create_ip",payParameter.getMch_create_ip());//终端IP
		map.put("return_url",payParameter.getReturn_url());//页面展示通知地址
		map.put("notify_url",payParameter.getNotify_url());//后台通知地址
		map.put("nonce_str", String.valueOf(new Date().getTime()));//随机字符串
		String strtosign = MapUtils.formatUrlMap(map, false, false);
		//TODO 查询商户相关数据  =payKey
		String signstr = MD5.sign(strtosign, "&payKey="+merchant.getPayKey() , "utf-8");
		if(!signstr.equals(payParameter.getSign())){
			return R.error("签名错误");
		}
		PayorderEntity payorder=new PayorderEntity();
		*//*
		resource: resource,
				busId: merchantId,
				codeNo: codeNo,
				payType:'0',//区分第三方还是 还是二维码发起支付
				category: '0',
				status: "0",
				amount: $("#amount").val(),
				payremark: $("#payremark").val(),
				openid: openid
		*//*

		payorder.setResource();//设置：来源（0 微信、1 支付宝）
		payorder.setRecordno(DefaultSequenceManager.get().next(BizSequenceType.TRANSQ));//订单号
		payorder.setOrderdate(new Date());
		payorder.setTimeoutdate(new Date(new Date().getTime() + 300000));// 订单超时5分钟
		payorder.setPayResult(Constant.PAY_RESULT_ERROR);
		payorder.setMchCreateIp(IPUtils.getIpAddr(request));
		////查询渠道商信息
		Map<String, Object> mapPayChannel = new HashMap<String, Object>();
		mapPayChannel.put("merchantNo", payorder.getBusid());
		mapPayChannel.put("payState", Constant.Status.ENABLE.getValue());//状态 0、删除 1、启用 2、禁用
		mapPayChannel.put("payType", Constant.PayType.PAY_SCAN_CODE.getValue());
		PayChannelEntity payChannel = payChannelService.queryPayBymerchantNo(mapPayChannel);
		if (payChannel == null || StringUtil.isEmpty(payChannel.getPayChannelNo()) ||
				StringUtil.isEmpty(payChannel.getPayRate()) || StringUtil.isEmpty(payChannel.getPayKey())) {
			logger.info("出现错误，请查看是否配置了【扫码支付】商户配置信息");
			return R.error("商户渠道参数错误");
		}
		payorder.setPayRate(payChannel.getPayRate());
		//结算金额  金额*签约汇率/100
		BigDecimal serviceCharge = payChannel.getPayRate().multiply(payorder.getAmount()).divide(BigDecimal.valueOf(100));
		payorder.setServiceCharge(serviceCharge);
		BigDecimal settlementAmount = payorder.getAmount().subtract(serviceCharge);
		payorder.setSettlementAmount(settlementAmount);
		payorder.setPaychannelId(payChannel.getPayChannelId());//支付渠道id



		payorderService.savePayNativeOrder(payorder,payChannel);

		return new ModelAndView("redirect:");
	}*/
    
    /**
     * 支付宝支付测试
     * @param request
     * @param modeMap
     * @param response
     * @throws Exception
     */
    @RequestMapping(value = "/auth/openWEB", method = RequestMethod.GET)
    public void openWEB(HttpServletRequest request, ModelMap modeMap,HttpServletResponse response) throws Exception {
        /*if (java.awt.Desktop.isDesktopSupported()) {
            try {
                // 创建一个URI实例
                java.net.URI uri = java.net.URI.create("http://www.baidu.com/");
                // 获取当前系统桌面扩展
                java.awt.Desktop dp = java.awt.Desktop.getDesktop() ;
                // 判断系统桌面是否支持要执行的功能
                if (dp.isSupported(java.awt.Desktop.Action.BROWSE)) {
                    // 获取系统默认浏览器打开链接
                    dp.browse( uri ) ;
                }
            } catch (Exception e) {
                e.printStackTrace() ;
            }
        }*/
        try {
            Runtime.getRuntime().exec("rundll32 url.dll,FileProtocolHandler http://www.baidu.com");
        } catch (Exception e) {
            e.printStackTrace() ;
        }
    }


    /**
     * 支付宝支付测试
     * @param request
     * @param modeMap
     * @param response
     * @throws Exception
     */
    @RequestMapping(value = "/auth/aliPay", method = RequestMethod.GET)
    public void aliPay(HttpServletRequest request, ModelMap modeMap,HttpServletResponse response) throws Exception {
    	String rsKey = "MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQCz4Rmfm2g4yWfIyxQBHVH4zLdbYJ80Dcv/SVYlQCu2V5S3unQnbrJDpnV9C7Y0aSi9iVu7kzEWrJCmqtbJ1nyyq5OGudnTUewMeFQNWMZwRczyF5K++D/VMWRqXRJDjSEDd2JrdSYIG0fU3iQy9P9pKk0RioZHf56gJXG1tIQum+z1oKh4zNge5x6iLc2LE87sPKl8PpPcVLqqHIdQE5eiRgr8TkTNPFsUpslo3HcA6s0wetx5fdDGJHqlhNMyH7FcRvHSolzFGsE9g9L1iwykbniPZd0oYM8BslZ0KAZ/hQWSZjv231hEVAwGwALNipXfnXFY0quu2GACscaqZBqjAgMBAAECggEAZxdDUC4I9UK4sGNy+5CKQkVRcJVXqMWffJfTP1Yft0lKemHp4A+ZKxxjiV8E9dSu/LGUWVRqdcxAusR+hP7gSKX8zuIE7Q+ucRclVODkGcRnSPgpqjksnErKegsNRJnFqe7qARwKx+qaqG0H4gx3tRYBRWRWwPNrPe031iO2/d54n6WLsaxbnJSfiaKkIfRDDGm4ycUtWlAEc5e9m/VTGozpRBlUxBTTyFU58ntubn74avroqBK8wD3YQdAB+6B/+6OI7dSyopZwYwQLeb0+Qjdsnsse2ieMZJpdlhS++c241m/BR9+xnxXSQJaQGr0BRdZCx5IJCJCHEEYXxUSagQKBgQDn/EtE0K2lvQsCxDyxTGi5cRlNQDto3eGmAbepIJMjr1ACS+E1HT+BGsI2jW1Si6+1J42SvqmxW4rknMB3S+BPBXM9/q16XtBPy38vySAVyU/q503YM3EtWxAbR1fDDNZMTEEqEyXol8bSawssBZQFd7YQCK72JnvCRMs7nk9U+wKBgQDGf/iQJ8Rf9a2t2F2F/n0HoHS7d7t43FWJNcBotg1a0DpUQWSoiq5VtxduU6ClWC+mm3hp7zR98cCflCJIFOeue+F3Z1tV8fq0qogOOSwKiyU2pSaz8xfTu2qndfi97GhCDTcsqhVpW3mkG8hax6fbCGCWYbf2INxRni+NpDvQeQKBgQCmQXHQB53rQeg6O1kj15bWD/AKJRZuuVWWG3T8iJPq5yF4A9mKr0NryzmUzxaiKenq8kXL/UiwCuMnpA9rb7155HYK4BKDuJ+iED0+ie2sr3HO76YiY/ugfbq1UhPbfb+3Po8VEFQCtYOQGZcQHY9Pu9OG+jIpxrq7J4JfX72LMQKBgQCpYwjEUvsTe/2ybQEZ19nvyS/zza+P6k2fodvIPxpUVX6A6bCw1m8APBZlkj1y+zbmcKMnmvVrSAI86tb6NcSis5nqH6vkQnLS+vbRVF5NvQGLiRDm3FmH19Wig1w5DeTGAKsFlTpiRqodrYuiU9/cXGC30zl9cfswNtGTiAN22QKBgExbo7GoWuojMxyoXwTnbXoTmwhtZfHEgz2K7Z39VNtvK/i4vPhAQhO1wq8RdXVT6yC+3SA2XpnOQqlHt2HU+LGUxsX0MuIZCmhLNq+3lpbJ67DPSMMTn8THYrO4T7IHzEQwxunQJ7POZDfS9jXREedp/8Co5yfNEpYaDhLFefzR";
    	String publicKey = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAgGMYilIyX9JfOY3qyT8wGyStEgOiqhcBnVwevLBGgCJhvlY8zk+ZwfdXcYg+Wo4GAVwqNk1AXfkcnRFlZC1H5m4XP1cPFEXTFb4Cz1F6B9iCbQREAYuphOsIf0hbtp9xZ8oMundwzdvsQFcQhIB/Uuod0TTrlV3j3r0zKEaJyKMeZ1oYisVxKMTQsd8TQ/aJvIZMk9Pl09MONWpOPbe+Nre12/r9G/IZva0Z683JTgR4ayaAQZ2rH0SbFC6CUKMWXXpaHQM/88ZuSiIbTA7r6GZ63EsNIc0SBkWC+PTavz3ikpxTULnjhGee5ZkqxiZ3EoPt+SpL5JgyphT3YzSY4wIDAQAB";
    	String aliPayKey = "2017071807796601";
    	AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do",
    			aliPayKey, rsKey, "json", "utf-8", publicKey, "RSA2"); //获得初始化的AlipayClient
    	AlipayTradeWapPayRequest alipayRequest = new AlipayTradeWapPayRequest();//创建API对应的request
        String returnUrl =  "http://www.iknowtec.cn";//前台通知地址
        String notifyUrl = "https://www.iknowtec.com";
    	alipayRequest.setReturnUrl(returnUrl);
    	alipayRequest.setNotifyUrl(notifyUrl);//在公共参数中设置回跳和通知地址
    	alipayRequest.setBizContent("{" + 
    	" \"out_trade_no\":\"2018010412345678\"," +
    	" \"total_amount\":\"88.88\"," +
    	" \"subject\":\"Iphone6 16G\"," +
    	" \"product_code\":\"QUICK_WAP_PAY\"" +
    	" }");//填充业务参数
    	String form="";
    	try {
    	form = alipayClient.pageExecute(alipayRequest).getBody(); //调用SDK生成表单
    	} catch (AlipayApiException e) {
    	e.printStackTrace();
    	}
    	response.setContentType("text/html;charset=" + "utf-8");
    	response.getWriter().write(form);//直接将完整的表单html输出到页面
    	response.getWriter().flush();
    	response.getWriter().close();
    }



}